package com.sikulifang.bank.simulation.util;

import cn.hutool.core.lang.Dict;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.sikulifang.bank.simulation.enums.BankEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName TemplateUtil
 * Description
 *
 * @author Yat
 * Date 2023年7月28日, 0028 17:03
 * version 1.0
 */
@Component
public class TemplateUtils implements InitializingBean {

    private Map<String, TemplateEngine> cacheMap = new HashMap<>();
    private static final TemplateEngine engine = TemplateUtil.createEngine(
            new TemplateConfig(
                    "/templates/bank/", TemplateConfig.ResourceMode.CLASSPATH
            )
    );

    /**
     * Description: 根据模板渲染数据
     * <p>
     * Date: 2023年7月28日, 0028 17:04
     *
     * @param templateName 模板名称
     * @param dict         数据
     * @return {@link String}
     */
    public String getTemplate(String templateName, Dict dict, BankEnum bankEnum) {
        // Template template = engine.getTemplate(templateName + ".ftl");
        Template template = cacheMap.get(bankEnum.name()).getTemplate(templateName + ".ftl");
        return template.render(dict);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        for (BankEnum bankEnum : BankEnum.values()) {
            String name = bankEnum.name();
            TemplateEngine engine = TemplateUtil.createEngine(
                    new TemplateConfig(
                            "/templates/bank/" + name + "/", TemplateConfig.ResourceMode.CLASSPATH
                    )
            );
            cacheMap.put(name, engine);
        }
    }
}
